﻿using AuthCenter.Domain;
using AuthCenter.ErorCode;
using AuthCenter.Infrastructure;
using AuthCenter_API.Read.Applications.Commands.RBAC;
using AuthCenter_API.Read.Dtos;
using MediatR;

namespace AuthCenter_API.Read.Applications.CommandHandlers.RBAC
{
    public class MenuTreeQueryCommandHandler : IRequestHandler<MenuTreeQueryCommand, APIResult<List<TreeSelectDto>>>
    {
        private readonly IBaseRepository<MenuModel> _menuRepository;

        public MenuTreeQueryCommandHandler(IBaseRepository<MenuModel> menuRepository)
        {
            _menuRepository = menuRepository;
        }

        public async Task<APIResult<List<TreeSelectDto>>> Handle(MenuTreeQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<TreeSelectDto>> result = new APIResult<List<TreeSelectDto>>();
            result.Code = APIEnum.QuerySuccess;
            result.Message = APIEnum.QuerySuccess.Desc();
            List<TreeSelectDto> list = new List<TreeSelectDto>();
            var alllist = _menuRepository.GetAll().ToList();
            var toplist = alllist.Where(x => x.PID == 0);
            foreach (var item in toplist)
            {
                TreeSelectDto dto = new TreeSelectDto();
                dto.value = item.MenuId;
                dto.label = item.MenuName;
                GetTreeName(alllist, dto);
                list.Add(dto);
            }
            result.Data = list;
            return await Task.FromResult(result);
        }
        private void GetTreeName(List<MenuModel> allList,TreeSelectDto tree)
        {
            var list = allList.Where(x => x.PID == tree.value);
            foreach (var item in list)
            {
                TreeSelectDto dto = new TreeSelectDto
                {
                    value = item.MenuId,
                    label = item.MenuName
                };
                tree.children.Add(dto);
                GetTreeName(allList,dto);   
            }
        }
    }
}
